import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { ToastController, AlertController, LoadingController } from '@ionic/angular';
import { CameraOptions, Camera } from '@ionic-native/camera/ngx';
import { FileTransfer } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor(
    private http: HttpClient,
    private storage: Storage,
    private toastController: ToastController,
    private alertController: AlertController,
    private camera: Camera,
    private loadingController: LoadingController,
    private router: Router) { }

  /**
   * 根据key获取
   */
  async getLocalData(key: string) {
    return await this.storage.get(key);
  }

  /**
   * 存储key、value
   */
  async setLocalData(key: string,value: string) {
    await this.storage.set(key, value);
  }

  /**
   * 获取Token
   */
  async getToken() {
    return await this.storage.get('token');
  }

  /**
   * 存储Token
   */
  async setToken(token: string) {
    await this.storage.set('token', token);
  }

  /**
   * 清除Token
   */
  async remove() {
    await this.storage.remove('token');
  }

  /**
   * 公司是否有权限
   */
  async hasPermission(permission:string){
    const permissions:string[]=await this.getLocalData('permissions');
    return permissions.includes(permission);
  }

  /**
   * 退出
   */
  logout() {
    this.remove();
    this.router.navigate(['login']);
  }

  /**
   * Toast消息提示
   */
  async presentToast(msg: string) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }


  /**
   * 弹窗提醒
   */
  async presentAlertConfirm(msg: string) {
    const alert = await this.alertController.create({
      cssClass: 'my-custom-class',
      header: '提醒',
      message: msg,
      buttons: [
        {
          text: '确定',
          role: 'cancel',
          cssClass: 'secondary'
        }
      ]
    });
    await alert.present();
  }

  /**
   * 显示加载
   */
  async presentLoading() {
    const loading = await this.loadingController.create({
      cssClass: 'my-custom-class',
      message: '正在加载...',
      duration: 500
    });
    await loading.present();
  }


  /**
   * 关闭加载
   */
  closeLoading() {
    this.loadingController.dismiss();
  }

  /**
   * 通过拍照获取照片
   */
  getPictureByCamera(options: CameraOptions = {}): Observable<string> {
    let ops: CameraOptions = Object.assign({
      sourceType: this.camera.PictureSourceType.CAMERA,
      destinationType: this.camera.DestinationType.FILE_URI // DATA_URL: 0 base64字符串, FILE_URI: 1图片路径
    }, options);
    return this.getPicture(ops);
  };

  /**
   * 通过图库获取照片
   */
  getPictureByPhotoLibrary(options: CameraOptions = {}): Observable<string> {
    let ops: CameraOptions = Object.assign({
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI // DATA_URL: 0 base64字符串, FILE_URI: 1图片路径
    }, options);
    return this.getPicture(ops);
  };

  /**
   * 使用cordova-plugin-camera获取照片
   */
  getPicture(options: CameraOptions = {}): Observable<string> {
    let ops: CameraOptions = Object.assign({
      sourceType: this.camera.PictureSourceType.CAMERA,// 图片来源,CAMERA:拍照,PHOTOLIBRARY:相册
      destinationType: this.camera.DestinationType.FILE_URI,// 默认返回base64字符串,DATA_URL:base64   FILE_URI:图片路径
      quality: 94,// 图像质量，范围为0 - 100
      // allowEdit: true,//选择图片前是否允许编辑
      encodingType: this.camera.EncodingType.JPEG,
      targetWidth: 1024,// 缩放图像的宽度（像素）
      targetHeight: 1024,// 缩放图像的高度（像素）
      saveToPhotoAlbum: false,// 是否保存到相册
      correctOrientation: true,// 设置摄像机拍摄的图像是否为正确的方向
      // mediaType: this.camera.MediaType.PICTURE
    }, options);
    return Observable.create(observer => {
      this.camera.getPicture(ops).then((imgData: string) => {
        if (ops.destinationType === this.camera.DestinationType.DATA_URL) {
          observer.next('data:image/jpg;base64,' + imgData);
        } else {
          observer.next(imgData);
        }
      }).catch(err => {
        if (err == 20) {
          this.presentAlertConfirm('没有权限,请在设置中开启权限');
          return;
        }
        if (String(err).indexOf('cancel') != -1) {
          return;
        }
        this.presentAlertConfirm('获取照片失败');
      });
    });
  };

}